<?php

namespace catchAdmin\system\controller;

use app\common\model\WorkbenchBlock;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use app\common\model\WorkbenchConfig as WorkModel;
use catchAdmin\system\request\WorkbenchConfigRequest;
use catchAdmin\system\request\GetBlockRequest;
use catcher\exceptions\FailedException;

class WorkbenchConfig extends CatchController
{
    /**
     * 获取全局配置
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        $ret = (new WorkModel())->getConditionData([],'id,name,link,sort,icon');
        return CatchResponse::success($ret);
    }

    /**
     * 新增
     * @param WorkbenchConfigRequest $request
     * @return \think\response\Json
     */
    public function save(WorkbenchConfigRequest $request): \think\response\Json
    {
        $req = $request->post();
        $req['sort'] = (int)$req['sort'];
        $req['deleted_at'] = 0;
        return CatchResponse::success((new WorkModel())->addData($req));
    }

    /**
     * 更新
     * @param string $id 主键
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update(string $id, CatchRequest $request): \think\response\Json
    {
        $req = $request->post();
        if (isset($req['sort']) && !empty($req['sort'])) {
            $req['sort'] = (int)$req['sort'];
        }
        return CatchResponse::success((new WorkModel())->saveData($id, $req));
    }

    /**
     * 删除
     * @param string $id
     * @return \think\response\Json
     */
    public function delete(string $id): \think\response\Json
    {
        return CatchResponse::success((new WorkModel())->destroy($id));
    }

    /**
     * 保存布局
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function saveBlock(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();
        if (!isset($req['item']) || empty($req['item'])) {
            throw new FailedException("缺少item参数");
        }
        $id = (new WorkbenchBlock())->column('id');
        if (!$id) {
            $ret = (new WorkbenchBlock())->addData(['item' => $req['item'], 'deleted_at' => 0]);
        }else{
            $ret = (new WorkbenchBlock())->saveData($id, ['item' => $req['item']]);
        }
        return CatchResponse::success($ret);
    }

    /**
     * 获取布局
     * @return \think\response\Json
     */
    public function getBlock(): \think\response\Json
    {
        $item = (new WorkbenchBlock())->column('item');

        $ret = [];
        if ($item) {
            $ret['item'] = $item[0];
        }
        return CatchResponse::success($ret);
    }
}